<?php

namespace app\home\middleware;


use app\customer\BizResponse;
use app\consts\Code;
use app\consts\Keywords;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class JwtAuth implements MiddlewareInterface
{
    use BizResponse;

    public function process(Request $request, callable $next) : Response
    {
        $auth = $request->header("Authorization","Bearer ");

        $token = substr($auth,7);

        try{
            \Firebase\JWT\JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            //解析jwt
            $decoded = JWT::decode($token, new Key(config("app.jwt.secret"), 'HS256'));
            //将user_id写入请求
            isset($decoded->{Keywords::USER_ID}) && $request->{Keywords::USER_ID} = (int)$decoded->{Keywords::USER_ID};

        }catch (ExpiredException $e){
            return $this->error(Code::TOKEN_EXPIRED);
        }catch (\Exception $e) {
            return $this->error(Code::TOKEN_INVALID);
        }

        $response = $next($request);

        return $response;
    }
}